package com.zuoqi.config.filter;

import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewRendererServlet;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;


/**
 * 解决sitemesh3装饰页面不能使用freemarker标签问题
 * Created by zhangbaoyu on 16/12/8.
 */
@WebFilter(filterName="freemarkerFilter",urlPatterns="*.ftl",dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.FORWARD})
public class FreemarkerFilter implements Filter {

    private Locale locale;

    private ApplicationContext ctx;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String localeStr = filterConfig.getInitParameter("locale");
        if(StringUtils.hasText(localeStr)){
            locale = new Locale(localeStr);
        }else {
            locale = Locale.getDefault();
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        if(ctx == null){
            ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(req.getSession().getServletContext());
            if(null == ctx){
                throw new ExceptionInInitializerError("spring context is not loaded!");
            }
        }
        try {
            String name = req.getRequestURI();
            String contextPath = req.getContextPath();
            name = name.substring(contextPath.length(), name.lastIndexOf(".ftl"));
            FreeMarkerViewResolver viewResolver = ctx.getBean(FreeMarkerViewResolver.class);
            View view = viewResolver.resolveViewName(name, locale);
            Map<String, Object> model = (Map<String, Object>) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE);
            view.render(model, req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    @Override
    public void destroy() {

    }
}
